import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from 'src/entities/user.entity';
import { InjectRedis } from '@nestjs-modules/ioredis';
import Redis from 'ioredis';

@Injectable()
export class RecommendationTask {
  private readonly logger = new Logger(RecommendationTask.name);

  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRedis() private readonly redis: Redis,
  ) {}

  @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT) // 每天零点执行
  async refreshRecommendations() {
    this.logger.log('开始刷新所有用户的视频推荐缓存');

    // 清除所有推荐缓存，让系统在下次请求时重新计算
    const recommendationKeys = await this.redis.keys('user:*:recommendations');
    if (recommendationKeys.length > 0) {
      await this.redis.del(...recommendationKeys);
    }

    this.logger.log(`已清除 ${recommendationKeys.length} 个用户的推荐缓存`);
  }
}